import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { AfMessageService, AfUpDownService, gw_code_g } from '@core';
import { _HttpClient } from '@delon/theme';
import { dateTimePickerUtil as dateUtil } from '@delon/util';
import { Observable } from 'rxjs';

export interface ExcelUploadRecord {
  currentQueueId?: number | '';
  business: string;
  title: string;
  showExtendedFields?: boolean;
  action?: string;
  sourceId?: string;
  remark?: string;
  extendedFields?: string;
  hintExtendedFields?: string;
}

@Injectable({
  providedIn: 'root'
})
export class AfExcelService {
  fileType = 'tablelist';

  constructor(
    private http: _HttpClient,
    private msg: AfMessageService,
    private updownSrv: AfUpDownService,
    private router: Router
  ) {}

  public get httpClient(): _HttpClient {
    return this.http;
  }

  public getMaxQueueID(business: any): Observable<any> {
    return this.http.get(`${gw_code_g}/excel/queue/max/id/${business}`);
  }

  // 导入 - 业务数据, 上传excel文件
  public getUploadExcelFileUrl(record: ExcelUploadRecord): string {
    return `${gw_code_g}/excel/upload?sourceId=${record.sourceId}&title=${record.title}&business=${record.business}&action=${record.action}&extendedFields=${record.extendedFields}`;
  }

  //导出业务数据
  public exportData(record: ExcelUploadRecord, queryParam: any) {
    return this.downFileForPost(`${gw_code_g}/excel/export/data/${record.business}`, `${record.title}列表`, queryParam);
  }

  //下载导入日志
  public exportLog(record: ExcelUploadRecord) {
    return this.downFileForGet(`${gw_code_g}/excel/export/log/${record.business}/${record.currentQueueId}`, `${record.title}导入日志`, '');
  }

  // 下载导入模版
  public downloadTemplateFile(record: ExcelUploadRecord) {
    window.open(`${gw_code_g}/excel/download/template?business=${record.business}`);
  }

  // 下载导入模版 -  推荐使用
  public downTemplateFile(record: ExcelUploadRecord) {
    this.updownSrv.downFileForGet(`${gw_code_g}/excel/download/template?business=${record.business}`, `${record.title}导入模版.xlsx`, '');
  }

  public downFileForPost(url: string, key: string, params: any) {
    const file = `${key}_${dateUtil.format(new Date(), 'yyMMddhhmmss')}.xlsx`;
    this.updownSrv.downFileForPost(url, file, params);
  }

  public downFileForGet(url: string, key: string, params: any) {
    const file = `${key}_${dateUtil.format(new Date(), 'yyMMddhhmmss')}.xlsx`;
    this.updownSrv.downFileForGet(url, file, params);
  }

  public navUploadLogView(record: ExcelUploadRecord) {
    const url = `/system/excel/queue?queueId=${record.currentQueueId}&fileName=&business=${record.business}`;
    this.router.navigateByUrl(url);
  }
}
